package com.canbot.u05;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.canbot.u05.activity.ConnectionLostActivity;
import com.canbot.u05.activity.MyRobotActivity;
import com.canbot.u05.api.RobotManager;
import com.canbot.u05.bean.CustomDialogue;
import com.canbot.u05.bean.StandbyVoice;
import com.canbot.u05.service.VersionUpdateService;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.PadSocketManager;
import com.canbot.u05.socket.SocketManager;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.CrashHandler;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.MyDbUtils;
import com.canbot.u05.utils.VolleyUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class MainApplication extends Application implements Application.ActivityLifecycleCallbacks {

        public static boolean DEBUG = true;

        public static final int SWITCHACTIVITY = 2;

        private static final String TAG = "MainApplication";

        private MulticastSocket ds;

        private String multicastHost = "224.0.0.1";

        private InetAddress receiveAddress;

        /**
         * 是否三方联网成功.
         */
        public static boolean isConnect = false; //是否连接成功

        public boolean downLoadSuccess = false; //是否下载成功

        public static boolean clickDisconnectButton = false; //是否点击断开机器人

        public static String ACTION_CONNECT_SUCCESS = "com.canbot.u05.isConnect";

        public ArrayList<StandbyVoice> mStandbyVoices = new ArrayList<>();

        public ArrayList<CustomDialogue> mCustomDialogues;

        public static MainApplication mainApplication;

        public static MainApplication getInstance() {
                return mainApplication;
        }

        private Handler mHandler = new Handler() {
                public void handleMessage(Message msg) {
                        switch (msg.what) {
                                case SWITCHACTIVITY:
                                        String actName = (String) msg.obj;
                                        if (actName != null && !actName.isEmpty()) {
                                                Intent intent = new Intent();
                                                intent.setClassName("com.canbot.u05", actName);
                                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                startActivity(intent);
                                        }
                                        break;

                                default:
                                        break;
                        }
                }
        };

        public static ImageLoader instance = ImageLoader.getInstance();

        @Override
        public void onCreate() {
                super.onCreate();
                mainApplication = this;
                CrashHandler.getInstance().init(this);
                RobotManager.getInstance().init(this);
                VolleyUtil.initVolley(this);

                //初始化universal image loader
                DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() //
                        .showImageForEmptyUri(R.drawable.ic_picture_loadfailed) //
                        .showImageOnFail(R.drawable.ic_picture_loadfailed) //
                        .cacheInMemory(true) //
                        .cacheOnDisk(true) //
                        .build();//
                ImageLoaderConfiguration config = new ImageLoaderConfiguration//
                        .Builder(getApplicationContext())//
                        .defaultDisplayImageOptions(defaultOptions)//
                        .writeDebugLogs()//
                        .build();//
                instance.init(config);
                this.registerActivityLifecycleCallbacks(this);

                //增加接受组播,获取胸部服务器ip,头部服务器ip
                getServerIp();
                parseVcc();// 解析自定义对话

                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        getProperties();
                }
                else {
                        this.registerReceiver(new BroadcastReceiver() {
                                public void onReceive(Context context, Intent intent) {
                                        getProperties();
                                }
                        }, new IntentFilter(Intent.ACTION_MEDIA_MOUNTED));
                }

        }

        private void getProperties() {
                final Properties p = new Properties();
                try {
                        final FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory().toString()
                                + "/ai/config.properties");
                        p.load(new InputStreamReader(in, "utf-8"));
                        in.close();
                }
                catch (FileNotFoundException e) {
                        e.printStackTrace();
                }
                catch (IOException e) {
                        e.printStackTrace();
                }

                //修改机器人的名字
                final String robotname = p.getProperty("robotname");
                if (!TextUtils.isEmpty(robotname)) {
                        Config.ROBOT_NAME = robotname;
                }

                //修改机器人自身热点名称前缀
                final String robotWifiNamePre = p.getProperty("robotWifiNamePrefix");
                if (!TextUtils.isEmpty(robotWifiNamePre)) {
                        Config.ROBOT_WIFI_NAME_PREFiX = robotWifiNamePre;
                }

                //修改机器人自身热点密码
                final String robotWifiPwd = p.getProperty("robotWifiPassword");
                if (!TextUtils.isEmpty(robotWifiPwd)) {
                        Config.ROBOT_WIFI_PASSWORD = robotWifiPwd;
                }


                //修改地图方案 步科思 slam
                final String isBuKeSi = p.getProperty("isBuKeSi");
                if (!TextUtils.isEmpty(isBuKeSi)) {
                        Config.isBuKeSi = Boolean.valueOf(isBuKeSi);
                }

        }
        /**
         * 解析 自定义对话
         */
        private void parseVcc() {
                mCustomDialogues = MyDbUtils.queryAll(this);
        }

        /**
         * 增加接受组播,获取胸部服务器ip,头部服务器ip
         */
        public void getServerIp() {

                new Thread(new Runnable() {

                        @Override
                        public void run() {
                                Logger.e(TAG, "开始监听组播信息");
                                try {
                                        ds = new MulticastSocket(8003);
                                        receiveAddress = InetAddress.getByName(multicastHost);
                                        ds.joinGroup(receiveAddress);
                                }
                                catch (IOException e) {
                                        e.printStackTrace();
                                }


                                byte buf[] = new byte[8192];
                                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                                while (true) {
                                        try {
//                        Logger.e(TAG,"等待下一个心跳");
                                                ds.receive(dp);
                                        }
                                        catch (IOException e) {
                                                e.printStackTrace();
                                        }

                                        String a = new String(dp.getData(), 0, dp.getLength());

                                        if (a.equals("I am 01")) {
                                                Logger.e(TAG, "收到 I am 01");
                                                IpMsgConst.SOCKET_HOST = dp.getAddress().toString().substring(1);
                                                IpMsgConst.HTTP_URL = "http://" + IpMsgConst.SOCKET_HOST + ":7755/";
                                                flag = true;
                                                Logger.e("I am 01", IpMsgConst.SOCKET_HOST);
//                            ToastTools.newInstance(getApplicationContext()).showText("SOCKET_HOST:"+IpMsgConst.SOCKET_HOST);
                                        }
                                        else if (a.equals("I am 02")) {
                                                Logger.e(TAG, "收到 I am 02");
                                                IpMsgConst.SOCKET_HOST2 = dp.getAddress().toString().substring(1);
                                                IpMsgConst.HTTP_URL_CHEST = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/";
                                                Logger.e("I am 02", IpMsgConst.SOCKET_HOST2);
                                        }

                                        Logger.e("ttt", "clickDisconneted="+clickDisconnectButton);
                                        if (!clickDisconnectButton &&!isConnect && IpMsgConst.SOCKET_HOST != null && IpMsgConst.SOCKET_HOST2 != null) {
//                            Logger.e("I am 02",IpMsgConst.SOCKET_HOST2);
                                                Logger.e("I am 02  I am 01", "全部连接成功 ,isConnect=true;");
//                            Toast.makeText(getApplicationContext(), "头部服务器ip: "+IpMsgConst.SOCKET_HOST+"------"+"胸部服务器ip: "+IpMsgConst.SOCKET_HOST2, Toast.LENGTH_SHORT).show();
                                                isConnect = true;
                                                Intent intent = new Intent();
                                                intent.setAction(ACTION_CONNECT_SUCCESS);
                                                getApplicationContext().sendBroadcast(intent);
                                                com.canbot.u05.update.ConstUtils.APP_DOWNLOAD_URL_PARENT = IpMsgConst.SOCKET_HOST2;
                                                startService(new Intent(MainApplication.this, VersionUpdateService.class));

                                                SocketManager.getInstance().init(MainApplication.this, new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                //通知机器人头部播放连接音频和动画,通知胸口播放联网成功的界面
                                                                //modified by liJie 连接成功只发送给头部，头部切换成功时 ，发送8672指令切换胸口界面
//                                                                MsgSendUtils.sendStringMsgToPad(MsgType.SEND_CONN_SUCCESS, "conn success");
                                                                MsgSendUtils.sendStringMsg(MsgType.SEND_CONN_SUCCESS, "conn success");
                                                                heartbeatHandler.sendEmptyMessage(0);
                                                                //测试
//                                    heartbeatHandler.sendEmptyMessageDelayed(0,1000);


                                                        }
                                                });

                                                PadSocketManager.getInstance().init(MainApplication.this);
//
                                                break;
                                        }
                                }
                        }
                }).start();

        }

        private static final int SEND_HEARTBEAT = 100;

        private boolean flag;

        int i = 0;

        int j = 0;

        final Handler heartbeatHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {

                        switch (msg.what) {
                                case 0: {
//                                        if (MsgSendUtils.sendStringMsg(1000, "Test " + i++)) {
//                                                Logger.e(TAG, "成功 " + i);
//                                        }
//                                        else {
//                                                Logger.e(TAG, "失败 " + j);
//                                                j++;
//
//
//                                        }
                                        MsgSendUtils.sendStringMsg(MsgType.MOBILE_PAD_HEARTBEAT, "test");
                                        sendEmptyMessageDelayed(0, 1 * 1000);

                                        break;
                                }


                                case SEND_HEARTBEAT:
                                        if (flag) {

                                                flag = false;
                                                Logger.e(TAG, "心跳检测,现在正常，继续等待下一个五秒.");

                                                //发送心跳指令
                                                heartbeatHandler.sendEmptyMessageDelayed(SEND_HEARTBEAT, 10 * 1000);
                                        }
                                        else {

                                                //很长时间收不到头部的心跳了，认为是网络断开.
                                                MainApplication.isConnect = false;
                                                MainApplication.clickDisconnectButton = true;
                                                IpMsgConst.SOCKET_HOST2 = null;
                                                IpMsgConst.SOCKET_HOST = null;

                                                //如果在首页，那么不会跳出界面.
                                                if (isMainActivityTop()) {
                                                        Logger.e(TAG, "MyRobotActivity");
                                                        heartbeatHandler.sendEmptyMessageDelayed(SEND_HEARTBEAT, 10 * 1000);
                                                }
                                                else {
                                                        //出现网络断开提示框.
                                                        Logger.e(TAG, "心跳检测,已经和服务器断开连接. ");
                                                        Intent intent = new Intent(getApplicationContext(), ConnectionLostActivity.class);
                                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                        startActivity(intent);
                                                }

                                        }
                                        break;
                        }
                }
        };

        /**
         * 判断mainactivity是否处于栈顶
         *
         * @return true在栈顶false不在栈顶
         */
        private boolean isMainActivityTop() {
                ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
                return name.equals(MyRobotActivity.class.getName());
        }


        @Override
        public void onTrimMemory(int level) {
                super.onTrimMemory(level);
        }

        @Override
        public void onTerminate() {
                super.onTerminate();
        }


        static List<Activity> activitiesList = new ArrayList<>();

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {

                activitiesList.add(activity);
                Logger.e("activitiesList--->" + activitiesList.toString());
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
                if (null != activitiesList && null != activity) {
                        activitiesList.remove(activity);
                }
        }

        /**
         * 销毁Activity
         *
         * @param name
         */
        public static void finishActivity(String name) {
                if (activitiesList != null && activitiesList.size() != 0) {
                        for (Activity activity : activitiesList) {
                                String className = activity.getClass().toString();
                                if (className.contains(name)) {
                                        activity.finish();
                                }
                        }
                }
        }


}
